'use strict';

function getUrlParam(variable) {
  const query = window.location.search.substring(1);
  const vars = query.split('&');
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split('=');
    if (pair[0] == variable) { return pair[1]; }
  }
  return (false);
}

new Vue({
  el: '#test',
  data: {
    tests: [],
    score: null,
    show: false,
    answers: [],
    id: getUrlParam('id'),
  },
  created() {
    this.getQuestions();
  },
  methods: {
    getQuestions() {
      console.log(decodeURI(getUrlParam('name')));
      const body = {
        name: decodeURI(getUrlParam('name')),
      };
      const that = this;
      $.ajax({
        url: '../getQuestion',
        type: 'GET',
        data: body,
        success(data) {
          console.log(data);
          that.tests = data;
        },
      });
    },
    sendAnswer() {
      const body = {
        testPaperID: this.id,
        answers: this.answers,
      };
      $.ajax({
        url: '../scoring',
        type: 'POST',
        data: body,
        success(data) {
          console.log(data);
          alert('得分: ' + data.score);
          window.location.href = '../mytest.html';
        },
        dataType: 'json',
      });
    },
    setAnswer(problemId, choiceItem) {
      let exsit = false;
      for (const i in this.answers) {
        if (this.answers[i].problemId === problemId) {
          exsit = true;
          this.answers[i].choiceItem = [ choiceItem ];
          break;
        }
      }
      if (!exsit) {
        this.answers.push({
          problemID: problemId,
          answersItem: [ choiceItem ],
        });
      }
      document.getElementById('answer-' + problemId).innerText = choiceItem;
    },
  },
});
